package com.wisdom.benefit.jufa.news;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wisdom.benefit.jufa.R;
import com.wisdom.benefit.jufa.base.BaseActivity;
import com.wisdom.benefit.jufa.net.RetrofitService;
import com.wisdom.benefit.jufa.utils.CommonUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class UploadCredentialsActivity extends BaseActivity {
    private TextView nameTv, bankTv, numTv, statusTv, moneyTv;
    private Button sureBtn, cancelBtn, submitBtn;
    private Dialog dialog;
    private View inflate;
    private TextView camera;
    private TextView pic;
    private TextView cancel;
    private ImageView iv, bgIv;
    private RelativeLayout bgRl;
    private static final int PHOTO_REQUEST = 1;
    private static final int CAMERA_REQUEST = 2;
    String pic64;
    private static final int PHOTO_CLIP = 3;
    private Long need1;
    private String need2;
    Bitmap decodedByte;
    private int ReceiptStatus;
    private double PayeeTurn;
    private boolean isClick = false;
    public Uri imageUri;

    @Override
    protected int getLayout() {
        return R.layout.activity_upload_credentials;
    }

    @Override
    protected void initViews() {
        //收款人姓名
        nameTv = findViewById(R.id.upload_cred_name_tv);
        //开户银行
        bankTv = findViewById(R.id.upload_cred_bank_tv);
        //银行卡号
        numTv = findViewById(R.id.upload_cred_num_tv);
        //确认
        sureBtn = findViewById(R.id.upload_cred_sure_btn);
        //取消、
        cancelBtn = findViewById(R.id.upload_cred_cancel_btn);
        //回单金额
        moneyTv = findViewById(R.id.upload_cred_money_tv);
        //上传凭证
        submitBtn = findViewById(R.id.upload_cred_submit_btn);
        //显示图片
        iv = findViewById(R.id.upload_cred_submit_iv);
        //图片大图
        bgIv = findViewById(R.id.upload_cred_iv);
        statusTv = findViewById(R.id.upload_cred_status_tv);
        //
        bgRl = findViewById(R.id.upload_cred_bg);
        need1 = getIntent().getLongExtra("PayeeId", 0);
        need2 = getIntent().getStringExtra("OrderId");
        ReceiptStatus = getIntent().getIntExtra("ReceiptStatus", 0);
        PayeeTurn = getIntent().getDoubleExtra("PayeeTurn", 0.0);
        moneyTv.setText(String.valueOf(PayeeTurn));
        if (ReceiptStatus == -1) {
            statusTv.setText("待上传凭证");
        } else if (ReceiptStatus == 0) {
            statusTv.setText("审核中");
        } else if (ReceiptStatus == 1) {
            statusTv.setText("审核成功");
        } else if (ReceiptStatus == 2) {
            statusTv.setText("驳回");
        }
        queryPayeeAgentBankByPayeeId(need1);
        setClick();
    }

    /**
     * 监听
     *
     * @return
     */
    private void setClick() {
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bgRl.setVisibility(View.VISIBLE);
                bgIv.setImageBitmap(decodedByte);
            }
        });
        bgRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bgRl.setVisibility(View.GONE);
            }
        });
        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                show();
            }
        });
        //确认
        sureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(pic64)) {
                    Toast.makeText(UploadCredentialsActivity.this, "请上传凭证", Toast.LENGTH_SHORT).show();
                } else {
                    if (isClick == false) {
                        isClick = true;
                        uploadReceipt(need2, need1, pic64, "");
                    }
                }
            }
        });
        //取消、
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected int getTitleStringRes() {
        return 0;
    }

    /**
     * 上传凭证点击查询接口
     */
    private void queryPayeeAgentBankByPayeeId(Long payeeId) {
        addDisposable(RetrofitService.getNetService()
                .queryPayeeAgentBankByPayeeId(payeeId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getCode() == 0) {
                        nameTv.setText(response.getData().getRealName());
                        bankTv.setText(response.getData().getBankDeposit());
                        numTv.setText(response.getData().getBankNumber());
                    } else {
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("查询失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }

    /**
     * 上传凭证接口
     */
    private void uploadReceipt(String orderId, Long payeeId, String voucher, String voucherType) {
        showProgressDialog("正在上传");
        addDisposable(RetrofitService.getNetService()
                .uploadReceipt(orderId, payeeId, voucher, voucherType)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getCode() == 0) {
                        finish();
                    } else {
                        isClick = false;
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    hideProgressDialog();
                    throwable.printStackTrace();
                    isClick = false;
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("上传失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }

    public void show() {
        dialog = new Dialog(getActivity(), R.style.DialogTheme);
        //填充对话框的布局
        inflate = LayoutInflater.from(getActivity()).inflate(R.layout.photo_dialog_item, null);
        //初始化控件
        camera = (TextView) inflate.findViewById(R.id.camera);
        pic = (TextView) inflate.findViewById(R.id.pic);
        cancel = (TextView) inflate.findViewById(R.id.cancel);
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(UploadCredentialsActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(UploadCredentialsActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                } else {
                    getCamera();
                    dialog.dismiss();
                }
            }
        });
        pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPhoto();
                dialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        //将布局设置给Dialog
        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
//       将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialog.show();//显示对话框
    }

    /**
     * 从相册选择图片来源
     */
    private void getPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, PHOTO_REQUEST);
    }

    /**
     * 从系统相机选择图片来源
     */
    private void getCamera() {

        imageUri = Uri.fromFile(getImageStoragePath(this));

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        //指定照片存储路径

        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        startActivityForResult(intent, CAMERA_REQUEST);
//        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//
//        startActivityForResult(intent, CAMERA_REQUEST);
    }

    /**
     * 设置图片保存路径
     *
     * @return
     */

    private File getImageStoragePath(Context context) {

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "temp.jpg");

            return file;

        }

        return null;

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_REQUEST:
                switch (resultCode) {
                    case -1://-1表示拍照成功
                        Bitmap bitmap = decodeUriBitmap(imageUri);

                        iv.setImageBitmap(bitmap);
//                        Bundle bundle = data.getExtras();
//                        Bitmap bitmap = (Bitmap) bundle.get("data");
                        decodedByte = bitmap;
                        Bitmap bm = compressImage(bitmap);
                        pic64 = bitmapToBase64(bm);

//                        byte[] decodedString = Base64.decode(pic64, Base64.DEFAULT);
//                        decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                        submitBtn.setEnabled(false);
                        break;
                }
                break;

            case PHOTO_REQUEST://从相册取
                if (data != null) {
                    Uri uri = data.getData();
                    try {
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
//                        Bitmap bm = compressImage(bitmap);
                        pic64 = bitmapToBase64(bitmap);
                        byte[] decodedString = Base64.decode(pic64, Base64.DEFAULT);
                        decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                        iv.setImageBitmap(decodedByte);
                        submitBtn.setEnabled(false);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //对相册取出照片进行裁剪

                }
                break;
        }
    }

    private Bitmap decodeUriBitmap(Uri uri) {

        Bitmap bitmap = null;

        try {

            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));

        } catch (FileNotFoundException e) {

            e.printStackTrace();

            return null;

        }

        return bitmap;

    }

    /*
     * bitmap转base64
     * */
    private static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 质量压缩方法
     *
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length / 1024 > 500) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

}
